package cn.wolfcode.luowowo.resolver;

import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.interceptor.ResolverUserInfo;
import cn.wolfcode.luowowo.redis.srevice.IUserRedisSrevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义的参数解析器 用于给userinfo注入数据,减少controller中的代码冗余
 */
public class UserinfoResolver implements HandlerMethodArgumentResolver {
    
    //注入方法
    @Autowired
    private IUserRedisSrevice redisSrevice;
    
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //发送请求后此方法执行一次,对映射方法进行解析,如果有符合条件的映射方法,
        // 就是说支持请求里面的参数 返回true 然后立马执行下面的resolveArgument方法进行参数注入
        //如果结果为false就不执行下面的方法
        return methodParameter.getParameterType() == UserInfo.class &&
                methodParameter.hasParameterAnnotation(ResolverUserInfo.class);
    }
    
    
    //此方法在supportsParameter返回的结果为true时才执行
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
       
        //获取token 这里没有requst 就用别的方法去获取
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("token");
        //然后获取用户的信息
        UserInfo userInfo = redisSrevice.judgeUserByKey(token);
        //返回交给springboot去管理
        return userInfo;
    }
}
